package com.community.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ElasticSearch配置文件
 */
@Configuration
public class ElasticSearchClientConfig {

    @Value("${es.client}")
    private String esHost;

    /**
     * 获取配置文件中的es信息
     * @param esHost
     * @return
     */
    private HttpHost[] getEsHttpHost(String esHost){
        String[] hosts = esHost.split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length] ;
        for (int i = 0; i < hosts.length; i++) {
            String host = hosts[i];
            String[] item = host.split(":");
            String address = item[0];
            Integer port = Integer.parseInt(item[1]);
            httpHosts[i] = new HttpHost(address,port,"http");
        }
        return httpHosts;
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(){
       return new RestHighLevelClient(RestClient.builder(getEsHttpHost(esHost)));
    }

}
